import extend from "extend";
import { importJs } from "./libs/load-file";
import { global } from "./libs/global";

const config = {
	release: true,
	apiServer: "/",
	apiServerSSRPrefix: "",
	siteTitle: "SSR",
	siteFavicon: "",
	profile: global.BUILD_PROFILE,
	basePath: global.BASE_PATH,
};

// BUILD_CONFIG defined in profile.js
async function initConfig(BUILD_CONFIG: Record<string, any>) {
	try {
		if (!import.meta.env.SSR) {
			await importJs(config.basePath + "profile.js?" + Date.now());
		}
		if (!import.meta.env.SSR && global.BUILD_CONFIG) {
			BUILD_CONFIG = global.BUILD_CONFIG;
		}
		config.profile = global.BUILD_PROFILE;
		Object.assign(config, BUILD_CONFIG);

		console.log(`build date: ${global.BUILD_DATE}`);
		console.log(`build version: ${global.BUILD_VERSION}`);
		console.log(`build profile: ${global.BUILD_PROFILE}/(${BUILD_CONFIG?.profile})`);
		console.log(`build base: ${config.basePath}`);
	} catch (error) {
		console.log("fail to load config", error);
	}

	if (config.profile) {
		extend(config, (config as any)[config.profile] || {});
	}

	if (!import.meta.env.SSR) {
		if (config.siteFavicon) {
			[...document.querySelectorAll("link[rel*=icon]")].forEach((link: any) => {
				link.href = config.siteFavicon;
			});
		}
		if (config.siteTitle) {
			document.title = config.siteTitle;
		}
	}
}

export { initConfig };
export default config;
